package controller

import (
	"EnjoyWorking/model"
	"EnjoyWorking/utils"
	"EnjoyWorking/web/service"
	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/hero"
	"strings"
)

func NewProjectController(app *iris.Application, party iris.Party) {
	var (
		user       = party.Party("/project")
		controller = Project{service: service.Project{}}
	)

	user.Post("/create", hero.Handler(controller.create)).Name = "创建项目"
	user.Get("/getAll", hero.Handler(controller.getAll)).Name = "获取所有项目"
	user.Get("/get", hero.Handler(controller.get)).Name = "获取单个项目"
	user.Put("/update", hero.Handler(controller.update)).Name = "编辑项目"
	user.Delete("/delete", hero.Handler(controller.delete)).Name = "删除项目"

	list := app.GetRoutes()
	for _, v := range list {
		if v.Method == "OPTIONS" {
			continue
		}
		if strings.Index(v.Path, "/api/project") != -1 {
			v.Description = "项目管理接口"
		}
	}
}

type Project struct {
	service service.Project
}

func (c *Project) create(ctx iris.Context) {
	var (
		code utils.Code
		err  error
		vo = new(model.Project)
	)

	if err = ctx.ReadJSON(&vo); err != nil {
		code = utils.CODE_SYS_PARSE_PARAMS_ERROR
		goto ERR
	}

	if err = utils.Validator().Struct(vo); err != nil {
		code = utils.CODE_SYS_PARSE_PARAMS_ERROR
		goto ERR
	}

	if err = c.service.Insert(vo); err != nil {
		goto ERR
	}

	utils.Ok_(ctx, utils.CODE_PROJECT_CREATE_OK)
	return
ERR:
	golog.Errorf("项目[%s]创建失败。原因：%s，错误：%s", vo.Name, code, err)
	utils.InternalServerError(ctx, code, err)
}

func (c *Project) getAll(ctx iris.Context) {
	var (
		err    error
		code   utils.Code
		total  int64
		result []*model.Project
		resultCopy []*model.ProjectCopy
	)

	if total, result, err = c.service.FindList(); err != nil {
		goto ERR
	}

	for _, v := range result {
		resultCopy = append(resultCopy, &model.ProjectCopy{*v})
	}

	utils.PaginationTableData(ctx, total, resultCopy)
	return
ERR:
	golog.Errorf("失败。原因：%s，错误：%s", code.String(), err)
	utils.InternalServerError(ctx, code, err)
}

func (c *Project) get(ctx iris.Context) {
}

func (c *Project) update() {

}

func (c *Project) delete() {

}
